﻿namespace Lee.Utility;

/// <summary>
/// 构造器模式
/// </summary>
public class CustomContainer
{
    void testMain()
    { 
        var builder = new ContainerBuilder();
        builder.AddTransient<SqlDbConnection>();
        builder.AddTransient<MySqlDbConnection>();

       var container = builder.Build();

    }
}
public interface IDbConnection
{

}
public class SqlDbConnection : IDbConnection
{

}

public class MySqlDbConnection : IDbConnection
{

}
public enum ServiceLifetime
{
    Transient,
    Scoped,
}
public class ServiceDescriptor
{
    public Type ServiceType { get; }
    public ServiceLifetime Lifetime { get; }

    public ServiceDescriptor(Type type, ServiceLifetime lifetime)
    {
        ServiceType = type;
        Lifetime = lifetime;
    }
}

public class IContainer
{
}

public class Container : IContainer
{
    private List<ServiceDescriptor> _services = new();

    public Container(List<ServiceDescriptor> services)
    {
        _services = services;
    }
}

public interface IContainerBuilder
{
    void Add(ServiceDescriptor descriptor);

    IContainer Build();
}

public class ContainerBuilder : IContainerBuilder
{
    private List<ServiceDescriptor> _services = new();

    public void Add(ServiceDescriptor descriptor)
    {
        _services.Add(descriptor);
    }

    public IContainer Build()
    {
        return new Container(_services);
    }
}

public static class IContainerBuilderExtensions
{
    public static void AddTransient<T>(this IContainerBuilder builder)
    {
        builder.Add(new ServiceDescriptor(typeof(T), ServiceLifetime.Transient));
    }

    public static void AddScoped<T>(this IContainerBuilder builder)
    {
        builder.Add(new ServiceDescriptor(typeof(T), ServiceLifetime.Scoped));
    }
}